<?php


namespace app\controller;

use app\BaseController;
use app\model\Comment;
use app\model\Info;
use app\model\Post;
use app\model\User;
use app\Request;
use think\facade\Db;
use think\facade\Filesystem;
class PostsController extends BaseController
{
    public function  insertPosts(Request $request){
        $param = $request->param(['title', 'content']);
        $img = $request->all('img');
        $user_id = $request->user_id;
        $this->validate($param,'PostsValidate.insertposts');

        Db::startTrans();
        try {
            $URL = '';
            if (!empty($img)){
                if (!$img->getSize() == 8000000){
                    return $this->returnJson(self::USER_ERROR,'上传图片过大');
                }
                if (!in_array($img->extension(),$this->mime())){
                    return $this->returnJson(self::USER_ERROR,'请上传正确的图片格式');
                }
                $root = $request->server('HTTP_HOST') .DIRECTORY_SEPARATOR . 'storage'.DIRECTORY_SEPARATOR ;
                $path = DIRECTORY_SEPARATOR . 'info'  ;
                $fileUrl = Filesystem::disk('public')->putFile($path,$img,'uniqid');

                $URL = 'http://'. $root . $fileUrl;
            }

            $time = time();
            $post_id = Post::insertGetId([
                'user_id' => $user_id,
                'title' => $param['title'],
                'hot' => 0,
                'createTime' => $time,
            ]);

            Info::insert([
                'user_id' => $user_id,
                'post_id' => $post_id,
                'content' => $param['content'],
                'image' => $URL,
                'createTime' => $time,
            ]);

            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            return $this->returnJson(self::SERVER_ERROR,'系统错误',$exception);
        }
        return $this->returnJson(self::SUCCESS,'cg',$post_id);


    }
    public function getUserPosts(Request $request){
        $order = $request->param('order',0);
        $user_id = $request->user_id;
        $page = $request->param('page',1);

        $posts = Post::where('user_id','=',$user_id);

        if ($order==0)$posts->order('createTime','desc');
        if ($order==1)$posts->order('hot','desc');
        $posts = $posts->page( $page ,10)
            ->select();

        foreach ($posts as $key){
            $key['createTime'] = $this->switchTime($key['createTime']);
            $infoList = Info::where('post_id','=',$key['id'])->field('content')->select();
            if (!empty($infoList[0])){
                $key['content'] = $infoList[0]['content'];
                $key['image'] = $infoList[0]['image'];
                $key['count'] =count($infoList)-1;
            }else{
                $key['content'] ='';
                $key['image'] = '';
                $key['count'] =0;
            }
        }
        return $this->returnJson(self::SUCCESS,'cg',$posts);
    }

    public function delPosts(Request $request){
        $id = $request->get('id');
        try {
            if (Post::where('id','=',$id)->count() == 0){
                return $this->returnJson(self::USER_ERROR,'无此帖子');
            }
            Post::destroy($id);
        }catch (\Exception $exception){
            return $this->returnJson(self::SERVER_ERROR,'系统错误',$exception);
        }
        return $this->returnJson(self::SUCCESS,'cg');
    }

    public function getIndexPosts(Request $request){
        $order = $request->param('order',0);
        $search = $request->param('search','');
        $page = $request->param('page',1);

        $posts = Post::whereLike('title','%'.$search.'%')->with(['userInfo'])->page( $page ,20);
        if ($order==0)$posts->order('createTime','desc');

        if ($order==1)$posts->order('hot','desc');

        $posts = $posts->select();

        foreach ($posts as $key){
            $key['createTime'] = $this->switchTime($key['createTime']);
            $infoList = Info::where('post_id','=',$key['id'])->field('content')->select();
            if (!empty($infoList[0])){
                $key['content'] = $infoList[0]['content'];
                $key['image'] = $infoList[0]['image'];
                $key['count'] =count($infoList)-1;
            }else{
                $key['content'] ='';
                $key['image'] ='';
                $key['count'] =0;
            }
        }

        return $this->returnJson(self::SUCCESS,'cg',$posts);
    }

    public function getPostsInfo(Request $request){
        $id = $request->get('id');

        Db::startTrans();
        try {
            $PostList =  json_decode(Post::where('id','=',$id)->find(),true);

            if (empty($PostList)){
                return $this->returnJson(self::USER_ERROR,'无此帖子');
            }
            $PostList['createTime'] = $this->switchTime($PostList['createTime']);
            $user_info = User::field('username,headImg')->find($PostList['user_id']);
            $PostList['username'] = $user_info['username'];
            $PostList['headImg'] = $user_info['headImg'];

            $infoList = Info::where('post_id','=',$id)->order('id','asc')->with(['comment'])->select();
            $PostList['content'] = $infoList[0]['content'];
            $PostList['image'] = $infoList[0]['image'];
            $PostList['info'] = array();

            foreach ($infoList as $key=>$value){
                if ($key !=0 ){
                    $value['createTime'] = $this->switchTime($value['createTime']);
                    $user_info = User::field('username,headImg')->find($value['user_id']);
                    $value['username'] = $user_info['username'];
                    $value['headImg'] = $user_info['headImg'];

                    foreach ($value['comment'] as $v){
                        $v['createTime'] = $this->switchTime($v['createTime']);
                        $user_info = User::field('username,headImg')->find($v['user_id']);
                        $v['username'] = $user_info['username'];
                        $v['headImg'] = $user_info['headImg'];
                    }
                    array_push(   $PostList['info'],$value);
                }
            }

            Post::where('id','=',$id)->update([
                'hot'=>$PostList['hot']+1
            ]);

            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            return $this->returnJson(self::SERVER_ERROR,'系统错误',$exception);
        }

        return $this->returnJson(self::SUCCESS,'cg',$PostList);
    }

    public function commentPost(Request  $request){
        $param = $request->param(['id', 'content']);
        $img = $request->all('img');
        $user_id = $request->user_id;
        $this->validate($param,'PostsValidate.commitPost');

        Db::startTrans();
        try {
            $URL = '';
            if (!empty($img)){
                if (!$img->getSize() == 8000000){
                    return $this->returnJson(self::USER_ERROR,'上传图片过大');
                }
                if (!in_array($img->extension(),$this->mime())){
                    return $this->returnJson(self::USER_ERROR,'请上传正确的图片格式');
                }
                $root = $request->server('HTTP_HOST') .DIRECTORY_SEPARATOR . 'storage'.DIRECTORY_SEPARATOR ;
                $path = DIRECTORY_SEPARATOR . 'info'  ;
                $fileUrl = Filesystem::disk('public')->putFile($path,$img,'uniqid');

                $URL = 'http://'. $root . $fileUrl;
            }

            $time = time();
            Info::insert([
                'user_id' => $user_id,
                'post_id' => $param['id'],
                'content' => $param['content'],
                'image' => $URL,
                'createTime' => $time,
            ]);

            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            return $this->returnJson(self::SERVER_ERROR,'系统错误',$exception);
        }
        return $this->returnJson(self::SUCCESS,'cg');
    }

    public function commentInfo(Request  $request){
        $param = $request->param(['id', 'info']);
        $user_id = $request->user_id;
        $this->validate($param,'PostsValidate.commitInfo');

        try {
            Comment::insert([
                'user_id' => $user_id,
                'info_id' => $param['id'],
                'content' => $param['info'],
                'createTime' => time(),
            ]);
        }catch (\Exception $e){
            return $this->returnJson(self::SERVER_ERROR,'系统错误',$e);
        }

        return $this->returnJson(self::SUCCESS,'cg');
    }
}